# TODO: Add comment
# 
# Author: broken
###############################################################################
library(raster)
library(base)
library(gstat)
library(RPostgreSQL)

dr=dbDriver("PostgreSQL")

query="SELECT aqstime,filename, filepath FROM apom.satresampall04_daily order by aqstime"
con=dbConnect(dr,dbname="fimo",host="192.168.0.4",port=5432,user="rasdaman",password="rasdaman")
rs=dbSendQuery(con,query)
listFile=fetch(rs,n=-1)
numberRow=nrow(listFile)
listCount=data.frame()
for(i in 1:numberRow){
	time=listFile[i,"aqstime"]
	orgFileName=trim(listFile[i,"filename"])
	filePath=trim(listFile[i,"filepath"])
	maskFileName=paste(substr(orgFileName,1,nchar(orgFileName)-4),"_mask.tif",sep="")
	fullFile=paste("/var/www/html/",filePath,maskFileName,sep="")
	
	rasterFile=raster(fullFile)	
	rasterValues=values(rasterFile)
	valid_pixcel=sum(!is.na(rasterValues))
	
	ratio=valid_pixcel/2024*100
	orgTime = as.POSIXct(strptime(time,"%Y-%m-%d %H:%M:%S"))
	diff=as.difftime("07:00:00","%H:%M:%S",units="hour")

	localTime=orgTime+diff
	
	localYear= format.Date(localTime,"%Y")
	localMonth= format.Date(localTime,"%m")
	
	if(ratio>=30){
		print(paste(localTime,localYear,localMonth,orgFileName,sep=" "))
		listCount=rbind(listCount,data.frame(aqstime=localTime,year=localYear,month=localMonth,filename=orgFileName))
	}
	
}
write.csv(listCount,"/home/phamha/Desktop/mod04.csv")
print("Done")

